package com.bhs.sansong.ui.discountCoupon;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bhs.sansong.R;
import com.bhs.sansong.adapter.LogisticsDiscountCouponAdapter;
import com.bhs.sansong.base.BaseActivity;
import com.bhs.sansong.base.BaseBean;
import com.bhs.sansong.base.Constants;
import com.bhs.sansong.bean.CouponSearchBean;
import com.bhs.sansong.net.NetCallBack;
import com.bhs.sansong.ui.dialog.AttachMoreDialog2;
import com.bhs.sansong.ui.dialog.CityPickerDialog;
import com.bhs.sansong.ui.dialog.MyClickListener2;
import com.bhs.sansong.utils.MyUtils;
import com.bhs.sansong.utils.ToastUtil;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.lxj.xpopup.XPopup;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 优惠券搜索
 */
public class CouponSearchActivity extends BaseActivity implements View.OnClickListener, NetCallBack {

    private TextView mTvType;
    private ImageView mIvType;
    private LinearLayout mLlCity;
    private TextView mTvStartCity;
    private TextView mTvEndCity;
    private EditText mEtCompanyName;
    private RecyclerView mRvList;
    private LogisticsDiscountCouponAdapter mAdapter;
    private int type = 2;
    private int page = 1;
    private SwipeRefreshLayout mRefreshLayout;


    @Override
    public int initLayout() {
        return R.layout.activity_coupon_search;
    }

    @Override
    public void initView() {
        TextView mTvTitle = findViewById(R.id.tv_title);
        mTvTitle.setText("优惠券搜索");
        mTvType = findViewById(R.id.tv_type);
        mIvType = findViewById(R.id.iv_type);
        mLlCity = findViewById(R.id.ll_city);
        mTvStartCity = findViewById(R.id.tv_start_city);
        mTvEndCity = findViewById(R.id.tv_end_city);
        mEtCompanyName = findViewById(R.id.et_company_name);
        mRvList = findViewById(R.id.rv_list);
        mTvStartCity.setOnClickListener(this);
        mTvEndCity.setOnClickListener(this);
        mIvType.setOnClickListener(this);
        mTvType.setOnClickListener(this);
        mRefreshLayout = findViewById(R.id.refreshLayout);
    }

    @Override
    public void initData() {
        mList.add("专线搜索");
        mList.add("公司名称");
        mAdapter = new LogisticsDiscountCouponAdapter();
        mRvList.setAdapter(mAdapter);
        mRvList.setLayoutManager(new LinearLayoutManager(mActivity));
        mAdapter.setEmptyView(LayoutInflater.from(this).inflate(R.layout.layout_empty, null));
        loadData("");
        mEtCompanyName.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索要做的操作
                    page = 1;
                    loadData(mEtCompanyName.getText().toString());
                    return true;
                }
                return false;
            }
        });

        //监听 刷新是回调
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                loadData("");
            }
        });

        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                page++;
                loadData("");
            }
        }, mRvList);

        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (mAdapter.getData().get(position).getCan_take() == 1) {
                    networkRequest(netApi.takeCoupon(mAdapter.getData().get(position).getId()), CouponSearchActivity.this, 555);
                    mAdapter.getData().get(position).setCan_take(0);
                    mAdapter.notifyItemChanged(position);
                }
            }
        });
    }

    Map<String, Object> map = new ArrayMap<>();

    private void loadData(String search_key) {
        map.put("keyword", search_key);
        map.put("type", type);
        map.put("start_city", mTvStartCity.getText().toString());
        map.put("end_city", mTvEndCity.getText().toString());
        map.put("limit", 10);
        map.put("page", page);
        networkRequest(netApi.couponSearchList(map), this);
    }

    private List<String> mList = new ArrayList<>();

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_type:
            case R.id.iv_type:
                AttachMoreDialog2 attachMoreDialog = new AttachMoreDialog2(mActivity, mList);
                new XPopup.Builder(mActivity).isTouchThrough(true).isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                        .atView(mTvType).hasShadowBg(false) // 去掉半透明背景
                        .asCustom(attachMoreDialog).show();
                attachMoreDialog.setMyClickListener(new MyClickListener2() {
                    @Override
                    public void onClick(String id, String info) {
                        attachMoreDialog.dismiss();
                        if (id.equals("专线搜索")) {
                            type = 2;
                            mEtCompanyName.setVisibility(View.GONE);
                            mLlCity.setVisibility(View.VISIBLE);
                        } else if (id.equals("公司名称")) {
                            type = 1;
                            mEtCompanyName.setVisibility(View.VISIBLE);
                            mLlCity.setVisibility(View.GONE);
                        }
                    }
                });
                break;
            case R.id.tv_start_city:
                bottomSelectCity();
                break;
            case R.id.tv_end_city:
                bottomSelectCity2();
                break;
        }
    }

    private CityPickerDialog cityPickerDialog;

    private void bottomSelectCity() {
        if (cityPickerDialog == null) {
            cityPickerDialog = new CityPickerDialog(mActivity);
            cityPickerDialog.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    mTvStartCity.setText(address[1]);
                    if (!TextUtils.isEmpty(mTvEndCity.getText())) {
                        loadData("");
                    }
                }
            });
        }

        cityPickerDialog.show();
        cityPickerDialog.cityPickerReuse.setCity(Constants.city);
    }

    private CityPickerDialog cityPickerDialog2;

    private void bottomSelectCity2() {
        if (cityPickerDialog2 == null) {
            cityPickerDialog2 = new CityPickerDialog(mActivity);
            cityPickerDialog2.setMyClickListener(new MyClickListener2() {
                @Override
                public void onClick(String id, String info) {
                    String[] address = info.split(",");
                    mTvEndCity.setText(address[1]);
                    if (!TextUtils.isEmpty(mTvStartCity.getText())) {
                        loadData("");
                    }
                }
            });
        }

        cityPickerDialog2.show();
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        if(requestCode==0) {
            CouponSearchBean bean = new Gson().fromJson(json, CouponSearchBean.class);
            mRefreshLayout.setRefreshing(false);
            if (bean.getCode().equals("1")) {
                if (page == 1) {
                    mAdapter.setNewData(bean.getData().getList());
                } else {
                    mAdapter.loadMoreComplete();
                    mAdapter.addData(bean.getData().getList());
                }
                if (MyUtils.isEmpty(bean.getData().getList())) {
                    mAdapter.loadMoreEnd();
                }
            }
        }else {
            BaseBean bean = new Gson().fromJson(json, BaseBean.class);
            if (bean.getCode().equals("1")) {
                ToastUtil.show("领取成功");
            }else {
                networkRequest(netApi.couponList("100", page), this);
            }
        }
    }



    @Override
    public void onFailure(int requestCode) {
        mRefreshLayout.setRefreshing(false);
        mAdapter.loadMoreComplete();
    }
}